
/**
 * 防抖函数。
 * @param func		函数
 * @param wait		等待事件
 * @param immediate	立即执行。
 * @returns {(function(...[*]=): void)|*}
 */
function debounce(func,wait){
	let timeout;
	return function (...args) {
		let context=this;
		if(timeout){
			clearTimeout(timeout);
		}
		timeout=setTimeout(function () {
			func.apply(context,args);
		},wait);
	}
}

/**
 * 深度克隆对象。
 * @param obj
 * @returns {any}
 */
function deepClone(obj){
	return JSON.parse( JSON.stringify(obj));
}




function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}
function randomId() {
	let $chars = 'abcdefghijklmnopqrstuvwxyz';
	let maxPos = $chars.length;
	let id = '';
	for (let i = 0; i < 7; i++) {
		id += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	id += (new Date().getTime() + "").substr(7);
	return id;
}
function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

/**
 * 将 export default {  替换成 {
 * @param text
 * @returns {*}
 */
function replaceDefault(text){
	text = text.replace(/export\s*?default\s*?\{/img, "export default {");
	let index=text.indexOf("export default {");
	if(index!=-1){
		text=text.substring(index + 14);
	}
	return text;
}


/**
 * 根据名称从url获取参数的值。
 * @param name
 * @returns {string|null}
 */
function getUrlParam (name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

function toChineseMoney (num) {
	var fraction = ['角', '分'];
	var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
	var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
	var head = num < 0? '欠': '';
	num = Math.abs(num);

	var s = '';

	for (var i = 0; i < fraction.length; i++) {
		s += (digit[Math.floor(num * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
	}
	s = s || '整';
	num = Math.floor(num);

	for (let i = 0; i < unit[0].length && num > 0; i++) {
		var p = '';
		for (var j = 0; j < unit[1].length && num > 0; j++) {
			p = digit[num % 10] + unit[1][j] + p;
			num = Math.floor(num / 10);
		}
		s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
	}

	return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}


function formatNumber(value,format){
	if(!value || value===0){
		return value;
	}
	format=format || ",";
	value=value.toString().split(".");  // 分隔小数点
	var arr=value[0].split("").reverse();  // 转换成字符数组并且倒序排列
	var res=[];
	for(var i=0,len=arr.length;i<len;i++){
		if(i%3===0&&i!==0){
			res.push(format);   // 添加分隔符
		}
		res.push(arr[i]);
	}
	res.reverse(); // 再次倒序成为正确的顺序
	if(value[1]){  // 如果有小数的话添加小数部分
		res=res.join("").concat("."+value[1]);
	}else{
		res=res.join("");
	}
	return res;
}

export default {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	debounce:debounce,
	deepClone:deepClone,
	randomId:randomId,
	replaceDefault:replaceDefault,
	getUrlParam,
	toChineseMoney,
	formatNumber,

}
